package com.aiden.app.common.widget

import android.content.Context
import android.support.design.widget.AppBarLayout
import android.support.design.widget.CoordinatorLayout
import android.util.AttributeSet
import android.view.View

/**
 * 解决ScrollingViewBehavior导致底部显示不全的问题
 *
 * @author yanggeng
 * @date 2019/2/21 下午6:01
 */
class FixScrollingFooterBehavior @JvmOverloads constructor(context: Context ?= null, attributeSet: AttributeSet ?= null) : AppBarLayout.ScrollingViewBehavior(context, attributeSet) {
    private var appBarLayout: AppBarLayout? = null
    override fun onDependentViewChanged(parent: CoordinatorLayout, child: View, dependency: View): Boolean {
        if (appBarLayout == null) {
            appBarLayout = dependency as AppBarLayout
        }

        val result = super.onDependentViewChanged(parent, child, dependency)
        val bottomPadding = calculateBottomPadding(appBarLayout!!)
        val paddingChanged = bottomPadding != child.paddingBottom
        if (paddingChanged) {
            child.setPadding(
                    child.paddingLeft,
                    child.paddingTop,
                    child.paddingRight,
                    bottomPadding)
            child.requestLayout()
        }
        return paddingChanged || result
    }

    private fun calculateBottomPadding(dependency: AppBarLayout): Int {
        val totalScrollRange = dependency.totalScrollRange
        return totalScrollRange + dependency.top
    }
}